package com.sduonline.isdapp.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.sduonline.isdapp.model.Web;

public class WebDao {

	private static ConnectionPool pool;

	public WebDao() {
		if (pool == null) {
			pool = ConnectionPool.getInstance();
		}
	}

	public boolean save(Web web) {
		Connection conn = pool.getConnection();
		String sql = "insert into isd_web(name,interface_url,homePage) values(?,?,?)";
		PreparedStatement ptmt = null;

		try {
			conn.setAutoCommit(false);

			ptmt = conn.prepareStatement(sql);

			ptmt.setString(1, web.getName());
			ptmt.setString(2, web.getInterface_url());
			ptmt.setString(3, web.getHomePage());

			ptmt.execute();
			conn.commit();
			ptmt.close();
			conn.close();

			return true;
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
				return false;
			}
			return false;
		} finally {
			try {
				if (ptmt != null) {
					ptmt.close();
				}
				if (conn != null) {
					conn.close();
				}

			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public Web getById(int id) {
		Connection conn = pool.getConnection();
		String sql = "select * from isd_web where id = ? ";
		PreparedStatement ptmt = null;

		try {
			ptmt = conn.prepareStatement(sql);
			ptmt.setInt(1, id);
			ResultSet rs = ptmt.executeQuery();

			Web web = new Web();
			if (rs.next()) {
				web.setId(rs.getInt("id"));
				web.setName(rs.getString("name"));
				web.setInterface_url(rs.getString("interface_url"));
				web.setHomePage(rs.getString("homePage"));
			} else {
				web = null;
			}
			ptmt.close();
			rs.close();
			conn.close();
			return web;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				if (ptmt != null) {
					ptmt.close();
				}
				if (conn != null) {
					conn.close();
				}

			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public List<Web> getAll() {
		Connection conn = pool.getConnection();
		String sql = "select * from isd_web ";
		PreparedStatement ptmt = null;

		try {
			ptmt = conn.prepareStatement(sql);
			ResultSet rs = ptmt.executeQuery();
			List<Web> webs = new ArrayList<>();

			while (rs.next()) {
				Web web = new Web();
				web.setId(rs.getInt("id"));
				web.setName(rs.getString("name"));
				web.setInterface_url(rs.getString("interface_url"));
				web.setHomePage(rs.getString("homePage"));

				webs.add(web);
			}
			ptmt.close();
			rs.close();
			conn.close();
			return webs;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				if (ptmt != null) {
					ptmt.close();
				}
				if (conn != null) {
					conn.close();
				}

			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

	}

}
